package com.controller;

import com.domian.Account;
import com.service.Accountservice;
import com.servlet.Getpoint;
import com.servlet.Mypoint;
import com.servlet.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("account")
public class Accountcontroller {
    @Autowired
    Getpoint getpoint;
    @Autowired
    Account account;
    @Autowired
    private Accountservice accountservice;
    @Autowired
    Server server;
    tread1 tread1;
    @RequestMapping("findall")
    public String findall(Model model) {
        List<Account>list=accountservice.findall();
        System.out.println(list);
        model.addAttribute("list",list);
        return "success";
    }
    @RequestMapping("save")
    public void save(Account account, HttpServletRequest request,
                     HttpServletResponse response) throws Exception{
        accountservice.save(account);
        response.sendRedirect(request.getContextPath()+"/account" +
                "/findall");
    }
    @RequestMapping("openservlet")
    @ResponseBody
    public Account openservlet(Account s,String name)throws Exception{
        tread1=new tread1(server);
        tread1.start();
        System.out.println(s);
        System.out.println(name);
        return s;
    }
    @RequestMapping("closerservlet")
    @ResponseBody
    public String closerservlet(){
        server.closeservlet();
        return "success";
    }
    @RequestMapping("getpoint")
    @ResponseBody
    public List<Mypoint> getpoint(){
        List<Mypoint>list=new ArrayList<>(getpoint.getPointsjiaozhun());
        getpoint.setPointsjiaozhun(new ArrayList<>());
        return list;
    }
    @RequestMapping("clearpoint")
    @ResponseBody
    public Boolean clearpoint(){
        try {
            getpoint.setPointsjiaozhun(new ArrayList<>());
            return true;
        }catch (Exception exception){
            return false;
        }
    }
    @RequestMapping("test")
    @ResponseBody
    public String test(){
        return "<form action=\"account/save\" method=\"post\">\n" +
                "    姓名：<input type=\"text\" name=\"name\"><br>\n" +
                "    钱：<input type=\"text\" name=\"money\"><br>\n" +
                "    <input type=\"submit\">\n" +
                "</form>";
    }
}
class tread1 extends Thread{
    Server server;
    public tread1(Server server) {
        this.server = server;
    }
    @Override
    public void run() {
            server.beginservlet();
    }
}
